package com.zhouyu.service;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import com.spring.BeanPostProcessor;
import com.spring.Component;

/**
 * @Description todo
 * @Author yubao
 * @Date 2021/11/14 20:19
 **/
@Component("")
public class ZhouYuBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        System.out.println("初始化前。。。");
        if (beanName.equals("userService")) {
            ((UserServiceImpl)bean).setName("武松打虎");
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        System.out.println("初始化后");

        if (beanName.equals("userService")) {
            Object proxyInstance = Proxy.newProxyInstance(ZhouYuBeanPostProcessor.class.getClassLoader(),
                    bean.getClass().getInterfaces(), new InvocationHandler() {
                        @Override
                        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                            System.out.println("代理逻辑");
                            return method.invoke(bean, args);
                        }
                    });
            return proxyInstance;
        }

        return bean;
    }
}
